using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Share;

namespace Tower
{
    public class BattleContral : MonoBehaviour
    {
        private Vector3 lastMousePosition;
        private bool isDragging = false;
        private Camera mainCamera;

        // 矩形选择相关变量
        private Vector3 selectionStartPosition;
        private Vector3 selectionEndPosition;
        private bool isSelecting = false;
        private LineRenderer selectionBorder;

        // Start is called before the first frame update
        void Start()
        {
            mainCamera = CameraMgr.Instance.GetCamera();
            SetCameraToMapCenter();
            CreateSelectionRect();
        }

        private void CreateSelectionRect()
        {
            // 使用LineRenderManager申请一个LineRenderer
            selectionBorder = LineRenderManager.Instance.GetLine();

            // 隐藏边框
            selectionBorder.gameObject.SetActive(false);
        }

        private void SetCameraToMapCenter()
        {
            var cameraRoot = CameraMgr.Instance.GetfirstCamera();
            if (cameraRoot != null)
            {
                // 计算地图中心位置（2D游戏，只处理X和Y轴）
                float centerX = BattleField.Instance.MapSizeX / 2.0f;
                float centerY = BattleField.Instance.MapSizeY / 2.0f;
                
                // 设置摄像机位置到地图中心（保持Z轴不变）
                Vector3 centerPosition = new Vector3(centerX, centerY, cameraRoot.transform.position.z);
                cameraRoot.transform.position = centerPosition;
            }
        }

        // Update is called once per frame
        void Update()
        {
            HandleCameraDrag();
            HandleSelection();
        }

        private void HandleSelection()
        {
            // 检查鼠标左键按下
            if (Input.GetMouseButtonDown(0)) // 0 表示鼠标左键
            {
                StartSelection();
            }

            // 检查鼠标左键释放
            if (Input.GetMouseButtonUp(0))
            {
                EndSelection();
            }

            // 如果正在选择，更新矩形
            if (isSelecting)
            {
                UpdateSelection();
            }

         
        }

        private void StartSelection()
        {
            isSelecting = true;
            selectionStartPosition = Input.mousePosition;
            selectionEndPosition = Input.mousePosition;
            
            // 显示选择边框
            if (selectionBorder != null)
            {
                selectionBorder.gameObject.SetActive(true);
                UpdateSelectionBorder();
            }
        }

        private void UpdateSelection()
        {
            selectionEndPosition = Input.mousePosition;
            UpdateSelectionBorder();
        }

        private void EndSelection()
        {
            isSelecting = false;
            
            // 隐藏选择边框
            if (selectionBorder != null)
            {
                selectionBorder.gameObject.SetActive(false);
            }
            
            // 这里可以添加选择物体的逻辑
            Debug.Log($"Selection from {selectionStartPosition} to {selectionEndPosition}");
        }

        private void OnDestroy()
        {
            // 释放LineRenderer回池子
            if (selectionBorder != null)
            {
                LineRenderManager.Instance.ReleaseLine(selectionBorder);
                selectionBorder = null;
            }

        }

        private void UpdateSelectionBorder()
        {
            if (selectionBorder == null || mainCamera == null) return;

            // 将屏幕坐标转换为世界坐标
            Vector3 worldStart = mainCamera.ScreenToWorldPoint(selectionStartPosition);
            Vector3 worldEnd = mainCamera.ScreenToWorldPoint(selectionEndPosition);
            
            // 确保Z坐标为0（2D游戏）
            worldStart.z = 0;
            worldEnd.z = 0;
            
            // 计算矩形的边界
            Vector2 min = new Vector2(Mathf.Min(worldStart.x, worldEnd.x), Mathf.Min(worldStart.y, worldEnd.y));
            Vector2 max = new Vector2(Mathf.Max(worldStart.x, worldEnd.x), Mathf.Max(worldStart.y, worldEnd.y));
            
            // 使用DrawRect函数绘制矩形边框
            selectionBorder.DrawRect(min, max, Color.green, 0.02f);
        }

        private void HandleCameraDrag()
        {
            // 检查鼠标右键按下
            if (Input.GetMouseButtonDown(1)) // 1 表示鼠标右键
            {
                isDragging = true;
                lastMousePosition = Input.mousePosition;
            }

            // 检查鼠标右键释放
            if (Input.GetMouseButtonUp(1))
            {
                isDragging = false;
            }

            // 如果正在拖动，移动摄像机
            if (isDragging)
            {
                Vector3 currentMousePosition = Input.mousePosition;
                Vector3 mouseDelta = currentMousePosition - lastMousePosition;

                // 移动摄像机（2D游戏，只处理X和Y轴，反向移动）
                Vector3 moveDirection = new Vector3(-mouseDelta.x, -mouseDelta.y, 0) * 0.01f;

                // 获取当前摄像机位置
                var cameraRoot = CameraMgr.Instance.GetfirstCamera();
                if (cameraRoot != null)
                {
                    Vector3 newPosition = cameraRoot.transform.position + moveDirection;

                    // 限制摄像机位置不超过地图边界
                    newPosition = ClampCameraPosition(newPosition);

                    cameraRoot.transform.position = newPosition;
                }

                lastMousePosition = currentMousePosition;
            }
        }

        private Vector3 ClampCameraPosition(Vector3 position)
        {
            // 获取地图边界
            int mapSizeX = BattleField.Instance.MapSizeX;
            int mapSizeY = BattleField.Instance.MapSizeY;

            // 计算摄像机视野范围
            if (mainCamera != null)
            {
                float cameraHeight = mainCamera.orthographicSize * 2.0f;
                float cameraWidth = cameraHeight * mainCamera.aspect;

                // 限制摄像机位置，确保不会看到地图外的区域
                // 摄像机中心位置应该在 [cameraWidth/2, mapSizeX - cameraWidth/2] 和 [cameraHeight/2, mapSizeY - cameraHeight/2] 范围内
                float minX = cameraWidth / 2.0f;
                float maxX = mapSizeX - cameraWidth / 2.0f;
                float minY = cameraHeight / 2.0f;
                float maxY = mapSizeY - cameraHeight / 2.0f;

                // 如果地图比摄像机视野小，则让摄像机居中
                if (maxX < minX)
                {
                    minX = maxX = mapSizeX / 2.0f;
                }
                if (maxY < minY)
                {
                    minY = maxY = mapSizeY / 2.0f;
                }

                position.x = Mathf.Clamp(position.x, minX, maxX);
                position.y = Mathf.Clamp(position.y, minY, maxY);
            }
            else
            {
                // 如果没有摄像机，使用简单的边界限制
                position.x = Mathf.Clamp(position.x, 0, mapSizeX);
                position.y = Mathf.Clamp(position.y, 0, mapSizeY);
            }

            return position;
        }
    }
}
